package com.hama.iotrust.common.mybatis.criteria;

import java.util.HashMap;
import java.util.Map;

import com.hama.iotrust.common.mybatis.criteria.Criteria;
import com.hama.iotrust.common.mybatis.criteria.CriteriaException;
import com.hama.iotrust.common.mybatis.criteria.Expression;

/**
 * BETWEEN (A, B) 表达式
 * 
 * @param <T>
 * @author 金建强(ptma@163.com)
 * @version 1.0.0
 * @since 2012-3-15 下午05:53:12
 */
public class BetweenExpression implements Expression {

    private String      m_propName;
    private String      m_columnName = null;
    private Object      m_value1;
    private Object      m_value2;

    private String      m_param1;
    private String      m_param2;

    private Criteria<?> m_crit;

    BetweenExpression(String propertyName, Object value1, Object value2){
        m_propName = propertyName;
        m_value1 = value1;
        m_value2 = value2;
    }

    public String getSql() {
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        if (m_columnName == null) {
            sb.append("< not bound:").append(m_propName).append(">");
        } else {
            sb.append(m_columnName);
        }
        m_param1 = m_propName + m_crit.nextParamSuffix();
        m_param2 = m_propName + m_crit.nextParamSuffix();
        sb.append(" BETWEEN #{" + Criteria.PARAM_PREFIX + m_param1 + "} and #{" + Criteria.PARAM_PREFIX + m_param2 + "})");
        return sb.toString();
    }

    public Map<String, Object> getParameter() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(m_param1, m_value1);
        map.put(m_param2, m_value2);
        return map;
    }

    public boolean verify(Criteria<?> criteria) {
        return criteria.hasProperty(m_propName) && criteria.checkType(m_propName, m_value1.getClass());
    }

    public void bind(Criteria<?> crit) throws CriteriaException {
        m_crit = crit;
        m_columnName = crit.toColumnName(m_propName);
    }
}
